package com.ai.vita.velocity.directive;

import com.ai.vita.template.TemplateLoader;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;

import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangyj on 2016/3/10.
 */
public class WidgetCreate extends Directive {

    @Override
    public String getName() {
        return "widgetCreate";
    }

    @Override
    public int getType() {
        return LINE;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        String widgetName, templateName, template,
                classification = context.get("classification") != null ? context.get("classification").toString() : "";
        Serializable options;
        //是否需要加载js、css等资源
        Boolean loadResource = true;
        Map be = (Map) context.get("be");
        if(be == null){
            //记录已经加载过的组件名称
            be = new HashMap();
        }
        int paramsNumber = node.jjtGetNumChildren();
        /**********      参数处理        ***********/
        if(paramsNumber == 0){
            widgetName = "";
            template = "没有指定模版名称！";
            options = null;
        }else{
            if(paramsNumber >= 2){
                //第二个入参，组件属性对象
                options = (Serializable) node.jjtGetChild(1).value(context);
            }else{
                options = null;
            }
            //第一个入参，组件名称
            widgetName = (String) node.jjtGetChild(0).value(context);
            templateName = widgetName + "-tpl";
            template = TemplateLoader.getTemplate(templateName, "html", classification);
            if(template == null){
                template = TemplateLoader.getNotFoundPrompt();
                if(template != null && !"".equals(template)){
                    template = template.replaceAll("_templateName_", templateName);
                }
            }
            //是否要加载js、css等资源（如果已经加载过，就不再加载）
            if(be.get(widgetName) != null){
                loadResource = false;
            }else {
                be.put(widgetName, true);
            }
        }
        /**********      模版处理        ***********/
        //为避免模版间参数互相污染，重置context
        //context.put("options",options);
        VelocityContext ctx = new VelocityContext();
        ctx.put("options", options);
        ctx.put("classification", classification);//传递模版分类
        ctx.put("be", be);//传递已经加载过资源的组件名
        ctx.put("version", context.get("version"));//传递当前的系统版本号
        //渲染模版
        rsvc.evaluate(ctx, writer, "", template);
        //加载js、css等资源
        if(loadResource && widgetName != null && !"".equals(widgetName)){
            //加载模版对应的组件（js）
            if(TemplateLoader.containTemplate(widgetName, "js")){
                String startScript = "script", scriptType = TemplateLoader.getProperties("scriptType");
                if(scriptType != null){
                    startScript += " type='"+scriptType+"'";
                }
                rsvc.evaluate(ctx, writer, "", "<"+startScript+">"+TemplateLoader.getTemplate(widgetName, "js")+"</script>");
                if(TemplateLoader.containTemplate(widgetName + ".extend", "js")){
                    rsvc.evaluate(ctx, writer, "", "<"+startScript+">"+TemplateLoader.getTemplate(widgetName + ".extend", "js")+"</script>");
                }
            }
            //加载模版对应的样式（css）
            if(TemplateLoader.containTemplate(widgetName, "css")){
                rsvc.evaluate(ctx, writer, "", "<style>"+TemplateLoader.getTemplate(widgetName, "css")+"</style>");
            }
        }
        return true;
    }
}